﻿using AutoMapper;
using MediatR;
using ProcurementManagement.Applcation.Command.VendorCommand;
using ProcurementManagement.Applcation.Command.VendorTypeCommand;
using ProcurementManagement.Domain.Dtos;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.VendorTypeCommandHandlers
{
    public class VendorTypeShowCommandHandlers : IRequestHandler<VendorTypeShowCommand, List<VendorTypeDto>>
    {
        protected readonly InterfaceVendorTypeRepository repository;
        protected readonly IMapper mapper;

        public VendorTypeShowCommandHandlers(InterfaceVendorTypeRepository repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        public async Task<List<VendorTypeDto>> Handle(VendorTypeShowCommand request, CancellationToken cancellationToken)
        {
            List<VendorType> categories = (await repository.GetAll()).ToList();
            List<VendorTypeDto> treeCategories = BuildTree(categories, request.id);
            return treeCategories;
        }
        static List<VendorTypeDto> BuildTree(List<VendorType> categories, int parentId)
        {

            return categories
                .Where(c => c.VTFatherId == parentId)
                .Select(c => new VendorTypeDto
                {
                    value = c.VendorTypeId,
                    label = c.VTName,
                    children = BuildTree(categories, c.VendorTypeId) // 递归构建子分类
                })
                .ToList();


        }
    }
}
